package cn.znk.kedis.master_slave_model.autoconfigure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;

/**
 * IntelliJ IDEA
 * project: kedis-spring-boot-starter
 *
 * @author shimi
 * @since 2021/11/22
 * @version 1.0.3
 */
@Configuration
@EnableCaching
@ConditionalOnWebApplication
@ConditionalOnProperty(
        prefix = RedisConfigureConstants.GLOBAL_CONFIGURE_PREFIX,
        value = "enable-cache",
        havingValue = "true"
)
public class RedisCacheAutoConfiguration {

    @Bean
    public CacheManager cacheManager(@Autowired @Qualifier("masterRedisTemplate") RedisTemplate redisTemplate) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }

}
